#include "Settings.h"

Settings::Data data;

Settings::Data* Settings::GetData()
{
	return &data;
}


bool Settings::Save()
{
	BinaryFileHelper bfh("settings.dat", ios::out | ios::binary);

	if (!bfh)
	{
		bfh.Close();
		return false;
	}

	bfh.Exceptions(ios::failbit|ios::badbit);

	try
	{
		#pragma warning(disable:4267) //disable warning "size_t -> int: possible loss of data
		int keyDevicesCount = data.KeyDevices.size();
		bfh.Write((char*)&keyDevicesCount, sizeof(keyDevicesCount));
		
		map<DWORD, tstring>::iterator keyDevice;
		for(keyDevice = data.KeyDevices.begin(); keyDevice != data.KeyDevices.end(); keyDevice++)
		{
			bfh.Write((char*)&keyDevice->first, sizeof(keyDevice->first));
			bfh.WriteString(keyDevice->second);
		}

		bfh.Write((char*)&data.Active, sizeof(data.Active));
		bfh.Write((char*)&data.LockAtUnplug, sizeof(data.LockAtUnplug));
		bfh.Write((char*)&data.Locked, sizeof(data.Locked));

		bfh.Close();
	}
	catch(...)
	{
		bfh.Close();
		return false;
	}

	return true;
}

bool Settings::Load()
{
	data.Active = false;
	data.LockAtUnplug = false;
	data.Locked = false;

	BinaryFileHelper bfh("settings.dat", ios::in | ios::binary);

	if (!bfh)
	{
		bfh.Close();
		return false;
	}
	
	bfh.Exceptions(ios::failbit | ios::badbit);

	try
	{
		int keyDevicesCount = 0;
		bfh.Read((char*)&keyDevicesCount, sizeof(keyDevicesCount));

		for (int i = 0; i < keyDevicesCount; i++)
		{
			DWORD serial = 0;
			bfh.Read((char*)&serial, sizeof(serial));
			tstring name = bfh.ReadString();

			data.KeyDevices[serial] = name;
		}

		bfh.Read((char*)&data.Active, sizeof(data.Active));
		bfh.Read((char*)&data.LockAtUnplug, sizeof(data.LockAtUnplug));
		bfh.Read((char*)&data.Locked, sizeof(data.Locked));

		bfh.Close();
	}
	catch(...)
	{
		bfh.Close();
		return false;
	}

	return true;
}
